import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        // 首页数据
        list: [
            {
                id: 1,
                title: "香蕉",
                img: "https://img1.baidu.com/it/u=637920038,1376804190&fm=253&fmt=auto&app=120&f=JPEG?w=650&h=405",
                count: 1,
                price: 10,
                check: true,
            },
            {
                id: 2,
                title: "苹果",
                img: "https://img0.baidu.com/it/u=1593189938,2678379788&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
                count: 1,
                price: 5,
                check: true,
            },
            {
                id: 3,
                title: "西瓜",
                img: "https://img1.baidu.com/it/u=3485504383,1014524777&fm=253&fmt=auto&app=138&f=JPEG?w=640&h=498",
                count: 1,
                price: 20,
                check: true,
            },
        ],
        // 购物车数据
        carList: []
    },
    getters: {
        // 总数量
        allCount(state) {
            return state.carList.reduce((prev, next) => {
                return prev + next.count
            }, 0)
        }
    },
    mutations: {
        ADD_CARLIST(state, { item }) {
            // 判断商品是否在购物车中
            const index = state.carList.findIndex(items => items.id === item.id)
            // 没有在购物车中
            if (index === -1) {
                state.carList.push(item)
            } else {
                // 已存在
                state.carList[index].count += 1
            }
        },
        // 点击购物车列中--
        DEL_CARLIST(state, { index }) {
            state.carList[index].count -= 1
        },
        // 删除
        REM_CARITEM(state, { index }) {
            state.carList.splice(index, 1)
        }
    }
})

export default store